<template>
	<view class="field-calendar field-form-item">
		<u-form-item :label="label" :required="required" :prop="prop">
			<view @click="showCalendar = !disabled && !readonly" style="width: 100%; height: 37px">
				<text v-if="showDate == null || showDate === ''" style="color: rgb(192, 196, 204)">{{ placeholder }}</text>
				<text v-else>{{ showDate }}</text>
			</view>
			<u-calendar ref="calendar" v-model="showCalendar" :toolTip="label" mode="date"
				:active-bg-color="getActiveBgColor" btn-type="primary" @change="onSelectDate" max-date="2050-01-01"/>
		</u-form-item>
	</view>
</template>

<script>
	import style from 'uni.scss';
	import { validateWidget } from '@/utils/validate.js';
	const dayjs = require('dayjs');
	const customParseFormat = require('dayjs/plugin/customParseFormat');
	dayjs.extend(customParseFormat);

	export default {
		name: 'fieldCalender',
		props: {
			label: {
				type: String
			},
			value: {
				type: [String, Date, Number]
			},
			prop: {
				type: String
			},
			placeholder: {
				type: String
			},
			color: {
				type: String,
				default: style.primary_color
			},
			confirmText: {
				type: String,
				default: '确定'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			readonly: {
				type: Boolean,
				default: false
			},
			required: {
				type: Boolean,
				default: false
			},
			rules: {
				type: Array
			},
			format: {
				type: String,
				default: 'YYYY-MM-DD'
			}
		},
		data() {
			return {
				showCalendar: false,
				dirty: false,
				currentDate: undefined,
				errorMessage: ''
			}
		},
		methods: {
			onChange(value) {
				let temp = value ? value.format(this.format) : undefined;
				this.$emit('input', temp);
				this.$emit('change', temp);
				this.showCalendar = false;
			},
			onOpenCalender() {
				let date = this.day ? new Date(this.day.valueOf()) : new Date();
				this.onSelectDate(date);
				if (this.$refs.calendar) this.$refs.calendar.reset(date);
				this.currentDate = this.day;
			},
			setDirty(dirty) {
				this.dirty = dirty;
			},
			getDirty() {
				return this.dirty;
			},
			onSelectDate(res) {
				this.$emit('input', res.result);
				this.$emit('change', res.result);
				this.showCalendar = false;
			},
			validateWidget() {
				return new Promise((resolve, reject) => {
					validateWidget(this.rules, this.value).then(res => {
						this.errorMessage = '';
						resolve();
					}).catch(e => {
						this.errorMessage = e;
						resolve(e)
					});
				});
			}
		},
		computed: {
			day() {
				if (this.value == null) return null;
				if (typeof this.value === 'string') {
					return dayjs(this.value, this.format);
				} else {
					return dayjs(this.value);
				}
			},
			showDate() {
				return this.day ? this.day.format(this.format) : undefined;
			},
			getActiveBgColor() {
				return !this.color ? style.primary_color : this.color;
			}
		}
	}
</script>

<style>
</style>